<script setup lang="ts">
import {wechatLogin} from "@/api/login";
import {useStorage} from "@/hooks/web/useStorage";
import {getMenuListApi} from "@/api/menu";
import {RouteRecordRaw, useRouter} from "vue-router";
import {usePermissionStore} from "@/store/modules/permission";

const {currentRoute, addRoute, push} = useRouter()
const permissionStore = usePermissionStore()
import {useAppStoreWithOut} from '@/store/modules/app'

const appStore = useAppStoreWithOut()
const {setStorage, getStorage} = useStorage()
let code = ref('')
let redirect_uri = 'https://bm.assist-cn.com/index#/login'
let baseUrl = 'https://bm.assist-cn.com/'
const state = 'WWLogin'
const agentid = 1000076
const appid = 'ww3880f8e10b36a886'
onMounted(() => {
  // 重定向 URL
  let urlCode = getQueryString('code')
  let token = getStorage(appStore.getUserInfo)
  //如果token存在 直接前往首页
  if (token) return window.location.href = baseUrl +'index'
  //如果url的code存在调取登录接口
  if (urlCode) {
    code.value = urlCode
    handleLogin()
  } else {
    if (isMobile()) {
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURI(redirect_uri)}&response_type=code&scope=snsapi_base&state=${state}&agentid=${agentid}#wechat_redirect`
    } else {
      window.location.href = 'https://login.work.weixin.qq.com/wwlogin/sso/login?login_type=CorpApp&appid=' + appid + '&agentid=' + agentid + '&redirect_uri=' + encodeURI(redirect_uri) + '&state=' + state
    }
  }
})

//区分是否是移动端端设备访问
const isMobile = () => {
  var userAgentInfo = navigator.userAgent;
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(userAgentInfo);
}

const getQueryString = (name) => {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg) //获取url中"?"符后的字符串并正则匹配
  var context = ''
  if (r != null) {
    context = decodeURIComponent(r[2])
  }
  reg = null
  r = null
  return context == null || context == '' || context == 'undefined' ? '' : context
}


const handleLogin = () => {
  wechatLogin({code: code.value}).then(res => {
    if (res) {
      setStorage(appStore.getUserInfo, res.data)
      getRole()
    }
  })
}

const getRole = async () => {
  let res = await getMenuListApi({role_id: getStorage('userInfo').role_id});
  if (res) {
    const routers = res.data.list || []
    setStorage('roleRouters', routers)
    setStorage('roleButtons', res.data.menu)
    await permissionStore.generateRoutes('frontEnd', routers).catch(() => {
    })
    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    window.location.href = baseUrl +'index'
  }
}

</script>

<template>

</template>
